﻿using System;
using System.Collections;
using System.Diagnostics.Contracts;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.Video;

public class VideoController : MonoBehaviour, IDragHandler, IPointerClickHandler
{
    [SerializeField] private VideoPlayer videoPlayer;
    [SerializeField] private Image videoProgress;
    [SerializeField] private Image playControllerImg;
    [SerializeField] private Sprite playSprite;
    [SerializeField] private Sprite pauseSprite;
    [SerializeField] private Text VideoTotalTime;
    [SerializeField] private Text VideoNowTime;
    [SerializeField] private Text VideoNametext;
    [SerializeField] private Slider audioSlider;

    public RenderTexture RD;
    private float videoTimeCount;

    /// <summary>
    /// 正在使用视频控件事件
    /// </summary>
    public event Action videoControlling;

    /// <summary>
    /// 视频暂停事件
    /// </summary>
    public event Action videoPause;

    private bool isPause;

    /// <summary>
    /// 当前视频的播放状态
    /// </summary>
    /// <value></value>
    public bool IsPause
    {
        get => isPause;
    }

    /// <summary>
    /// 当前要播放视频的名称
    /// </summary>
    public string VideoName = string.Empty;

    public GameObject videoPanel;


    private void OnEnable()
    {
        if (this.VideoName == string.Empty)
        {
            Debug.LogError("视频名称不能为空");
            return;
        }

        ;
        Init();
    }

    private void Start()
    {
        if (this.VideoName == string.Empty) return;

        audioSlider.onValueChanged.AddListener(SetVideoAuido);

        videoPlayer.loopPointReached += (vd) =>
        {
            playControllerImg.sprite = pauseSprite;
            videoPause?.Invoke();
            isPause = true;
        };
        videoPlayer.prepareCompleted += (v) =>
        {
            videoTimeCount = (float) videoPlayer.length;

            VideoTotalTime.text = ((int) videoTimeCount / 60).ToString("D2") + ":" +
                                  ((int) (videoTimeCount) % 60).ToString("D2");

            UpdateVideoTimeText();

            playControllerImg.sprite = playSprite;
        };
        videoPlayer.Prepare();
    }

    /// <summary>
    /// 对视频信息执行一些初始化
    /// </summary>
    private void Init()
    {
        videoPlayer.source = VideoSource.Url;

        videoPlayer.url = LoadVideoByStreamFolder(VideoName);

        VideoNametext.text = VideoName;
    }

    /// <summary>
    /// 打开并播放指定视频
    /// </summary>
    /// <param name="videoname">播放视频的名字，视频放在StreamingAssets下</param>
    public void OpenAndPlayByName(string videoname)
    {
        //如果为切换视频
        // if (this.videoName!=string.Empty&&this.videoName.Equals(videoName)&&videoPanel.activeSelf)Init();
        this.VideoName = videoname;
        videoPanel.gameObject.SetActive(true);
    }

    /// <summary>
    /// 关闭当前视频面板，释放视频资源
    /// </summary>
    public void CloseVideo()

    {
        RD.Release();
        RD.DiscardContents();
        videoPlayer.Stop();
        videoProgress.fillAmount = 0;
        videoPanel.gameObject.SetActive(false);
    }

    /// <summary>
    /// 暂停、播放视频控制
    /// </summary>
    public void PlayController()
    {
        if (videoPlayer.isPlaying)
        {
            videoPlayer.Pause();
            isPause = true;
            playControllerImg.sprite = pauseSprite;
            videoPause?.Invoke();
        }
        else
        {
            videoPlayer.Play();
            isPause = false;
            playControllerImg.sprite = playSprite;
            videoControlling?.Invoke();
        }
    }

    private void Update()
    {
        if (videoPlayer.frameCount > 0)
        {
            UpdateVideoTimeText();
        }
    }

    private string LoadVideoByStreamFolder(string videoName)
    {
        string path = "file://" + Application.streamingAssetsPath + "/" + videoName + ".mp4";
        return path;
    }

    /// <summary>
    /// 更新视频的播放时间
    /// </summary>
    private void UpdateVideoTimeText()
    {
        videoProgress.fillAmount = ((float) videoPlayer.frame / (float) videoPlayer.frameCount);

        VideoNowTime.text = ((int) videoPlayer.time / 60).ToString("D2") + ":" +
                            ((int) videoPlayer.time % 60).ToString("D2");
    }

    public void OnDrag(PointerEventData eventData)
    {
        TrySkip(eventData);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        TrySkip(eventData);
    }

    private void TrySkip(PointerEventData eventData)
    {
        Vector2 localPoint;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(videoProgress.rectTransform, eventData.position,
            null, out localPoint))
        {
            float pct = Mathf.InverseLerp(videoProgress.rectTransform.rect.xMin,
                videoProgress.rectTransform.rect.xMax,
                localPoint.x);
            SkipToTarget(pct);
        }
    }

    private void SkipToTarget(float pct)
    {
        var frame = videoPlayer.frameCount * pct;
        videoPlayer.frame = (long) frame;
        videoPlayer.Play();
        isPause = false;
        videoControlling?.Invoke();
        playControllerImg.sprite = playSprite;
    }

    private void SetVideoAuido(float v)
    {
        videoControlling?.Invoke();
        if (videoPlayer.canSetDirectAudioVolume)
        {
            videoPlayer.SetDirectAudioVolume(0, v);
        }
    }
}